package com.qf.smsplatfrom.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.smsplatfrom.cache.BlackListCaChe;
import com.qf.smsplatfrom.constans.ResultCode;
import com.qf.smsplatfrom.events.UpdateBlackEvents;
import com.qf.smsplatfrom.exceptions.MyBaseException;
import com.qf.smsplatfrom.exceptions.PhoneBaseException;
import com.qf.smsplatfrom.exceptions.UpdateDataException;
import com.qf.smsplatfrom.mapper.BlackListMapper;
import com.qf.smsplatfrom.pojo.CheckType;
import com.qf.smsplatfrom.pojo.MyAuthUser;
import com.qf.smsplatfrom.pojo.TAdminUser;
import com.qf.smsplatfrom.pojo.TBlackList;
import com.qf.smsplatfrom.service.TBlackListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class TBlackListServiceImpl implements TBlackListService {
    @Autowired
    private BlackListMapper blackListMapper;
    private ApplicationContext context;
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }
    private BlackListCaChe caChe;
    @Autowired
    public void setCaChe(BlackListCaChe caChe) {
        this.caChe = caChe;
    }

    @Override
    public TBlackList showById(Long id) {
        if (ObjectUtils.isEmpty(id) || id <= 0) {
            throw new MyBaseException("传递的主键不合适", ResultCode.PK_NOT_ALLOW);
        }
        //return blackListMapper.findBlackById(id);
        return caChe.getByKey(id);
    }

    @Override
    public void addTBlackList(TBlackList tBlackList) {
        //判断格式是否正确
        if(tBlackList.isNull(CheckType.ADD)){
            throw new PhoneBaseException("手机号格式不符合规范",ResultCode.PHONE_NUM_ERROR);
        }
        blackListMapper.addBlack(tBlackList);

        //发布一个新事件
        //作用是更新缓存
        UpdateBlackEvents updateBlackEvents = new UpdateBlackEvents();
        context.publishEvent(updateBlackEvents);

    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public PageInfo<TBlackList> showAll(Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        //List<TBlackList> blackListList = blackListMapper.showAll();
        //PageInfo<TBlackList> pageInfo = new PageInfo<>(blackListList);
        //获取缓存中的数据
        List<TBlackList> blackList = caChe.getAllData();
        //获取user中的对象
        MyAuthUser principal = (MyAuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        //Object user = ((ServletRequestAttributes) requestAttributes).getRequest().getSession().getAttribute("user");
        //stream流的写法后边的connectors。tolist是固定格式写法
        List<TBlackList> collect = blackList.stream().filter(black -> {
            return black.getOwntype() == 1 || black.getCreater() == principal.getId()||principal.getType()==1;
        }).collect(Collectors.toList());
        //跳过pagenum-1条，截取limit（pagesize条）
        List<TBlackList> collect1 = collect.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        //分页数据存入
        PageInfo<TBlackList> pageInfo = new PageInfo<>(collect1);
        //手动存入总条数
        pageInfo.setTotal(collect.size());
        return pageInfo;
    }

    @Override
    public void updateBlack(TBlackList tBlackList) {
        //判断传过来的格式正确不正确
        if(tBlackList.isNull(CheckType.UPDATE)){
            throw new UpdateDataException("传递的数据不合规",ResultCode.DATA_ISNULL);
        }
        //根据id查询用户对象
        TBlackList blackById = blackListMapper.findBlackById(tBlackList.getId());
        //判断是否是管理员，以及判断你登陆的是哪个用户
        if(tBlackList.getOwntype()!=1&&blackById.getCreater()!=tBlackList.getCreater()){
            throw new UpdateDataException("你无权更新这条数据",ResultCode.NO_PERMISSON);
        }
        //调用修改方法
        blackListMapper.updateBlack(tBlackList);
        //发送一个新的事件,通知其该更新缓存
        context.publishEvent(new UpdateBlackEvents());
    }

    @Override
    public void deleteBlack(List<Integer> ids) {
        //获取到当前登录的用户对象
        MyAuthUser principal = (MyAuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        //Object user = ((ServletRequestAttributes) requestAttributes).getRequest().getSession().getAttribute("user");
        //判断用户是否是管理员
        if(principal.getType()==1){
            //调用管理员专属的删除方法
            blackListMapper.deleteBlackId(ids);
        }else{
            //调用普通员工的删除方法
            blackListMapper.deleteNoBlackId(ids,principal.getId());
        }
        //发布一个事件，通知它该更新缓存了
        context.publishEvent(new UpdateBlackEvents());
    }
}
